if(typeof Solid == 'undefined'){
	Solid = {increment: 0};
}

/*
 * data = [{id: 1, text: 'abc'},...]
 */
Solid.List = function(container, data, btnClick){
	var i = Solid.increment ++;
	this.filterId = "filter" + i;
	this.listId = "list" + i;
	this.btnClick = btnClick;
	var html = [];
	html.push('<input class="form-control" id="'+ this.filterId +'">');
	html.push('<div id="'+this.listId+'" class="solid_list"></div>');
	container.html(html.join(''));
	
	this.data = data;
	this.filtered = [];
	for (var i = 0; i < data.length; i++) {
		this.filtered.push(data[i]);
	}
	
	this.renderItem();
	
	var me = this;
	$("#" + this.filterId).keydown(function(e){
		if(e.keyCode == 13){
			me.filter(this.value);
		}
	})
}

Solid.List.prototype.renderItem = function(){
	var html = [];
	for (var i = 0; i < this.filtered.length; i++) {
		var item = this.filtered[i];
		var id = item.id || i;
		html.push('<input type="button" id="'+(this.listId + '_' + id)+'" class="btn btn-default" value="'+(item.text)+'">')
	}
	$('#' + this.listId).html(html.join(''));
	var click = this.btnClick;
	$('#' + this.listId + ' input').click(function(){
		var id = this.id.substring(this.id.indexOf('_') + 1);
		var text = this.value;
		click(id, text, this);
	})
}

Solid.List.prototype.filter = function(key){
	key = $.trim(key);
	this.filtered = [];
	for (var i = 0; i < this.data.length; i++) {
		if(!key || this.data[i].text.indexOf(key) > -1){
			this.filtered.push(this.data[i]);
		}
	}
	this.renderItem();
}

Solid.List.prototype.remove = function(itemId){
	var data = [];
	for (var i = 0; i < this.data.length; i++) {
		var x = this.data[i];
		if(itemId != x.id){
			data.push(x);
		}
	}
	this.data = data;
	
	data = [];
	for (var i = 0; i < this.filtered.length; i++) {
		var x = this.filtered[i];
		if(itemId != x.id){
			data.push(x);
		}
	}
	this.filtered = data;
	this.renderItem();
}

Solid.List.prototype.add = function(item){
	this.data.push(item);
	var key = $("#" + this.filterId).val();
	if(!key || item.text.indexOf(key) > -1){
		this.filtered.push(item);
	}
	this.renderItem();
}

Solid.List.prototype.addAll = function(data){
	this.data = data;
	this.filtered = [];
	for (var i = 0; i < data.length; i++) {
		this.filtered.push(data[i]);
	}
	this.renderItem();
}
